package com.peng.mvvm_wan.viewmodels

import android.text.TextUtils
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import com.peng.mvvm_wan.beans.ArticleBean
import com.peng.mvvm_wan.beans.BaseResp
import com.peng.mvvm_wan.beans.SearchResult
import com.peng.safety.utils.CODE_SUCC
import com.peng.safety.utils.SnackUtil

class SearchModel : BaseModel() {

    var selections = MutableLiveData<LinkedHashSet<String>>()
    var inputKey = MutableLiveData<String>("")
    var currentPageNum = 0
    var searchResultList = MutableLiveData<ArrayList<ArticleBean>>()
    var loadMoreStatus = MutableLiveData<LoadStatus>()

    init {
        selections.value = LinkedHashSet()
    }

    fun doSearch(loadMore:Boolean = false) {
        if (!loadMore) {
            currentPageNum = 0
        }
        apiDSL<BaseResp<SearchResult>> {
            onRequest {
                service.requestSearch(currentPageNum, inputKey.value!!)
            }

            onResponse {
                if (it.errorCode == CODE_SUCC) {
                    if (loadMore) {
                        if (it.data == null || it.data!!.datas == null || it.data!!.datas!!.isEmpty()) {
                            loadMoreStatus.value = LoadStatus.END
                        }else {
                            searchResultList.value?.addAll(it.data?.datas ?: emptyList())
                            searchResultList.value = searchResultList.value
                            loadMoreStatus.value = LoadStatus.COMPLETE
                        }
                    }else{
                        searchResultList.value = it.data?.datas
                    }
                } else {
                    loadMoreStatus.value = LoadStatus.FAIL
                    SnackUtil.show(it.errorMsg, false)
                }
            }

            onError {
                SnackUtil.show(it.message, false)
                loadMoreStatus.value = LoadStatus.FAIL
                true
            }
        }
    }

    fun loadMore() {
        currentPageNum++
        doSearch(true)
    }

    enum class LoadStatus {
        COMPLETE, FAIL, END
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun startSearch() {
        if (TextUtils.isEmpty(inputKey.value)/* && searchResultList.value?.isEmpty() != false*/) {
            doSearch()
        }
    }

}